package org.kk.ds.stack;

import java.util.EmptyStackException;

/**
 * 实现数据结构: 栈
 * @author kk
 * @Date 2021/2/4
 */
public class StackDemo {
    private Integer[] data;
    private int length;

    public StackDemo() {
        this(10);
    }

    public StackDemo(int i) {
        this.data = new Integer[i];
    }
    public int dateLength(){
        return data.length;
    }
    public boolean isEmpty() {
        return length == 0;
    }

    public int size() {
        return length;
    }

    public int push(int i) {
        if (data.length == size()) {
            expansion(size() << 1);
        }
        data[length++] = i;
        return i;
    }
    public int top(){
        checkIsEmptyStack();
        return data[0];
    }
    public int pop() {
        checkIsEmptyStack();
        int result = data[--length];
        data[length] = null;
        if (length > 0 && length == data.length >> 2) expansion(data.length >> 1);
        return result;
    }
    private void checkIsEmptyStack(){
        if(isEmpty()){
            throw new EmptyStackException();
        }
    }
    public void expansion(int i) {
        if (i < size()) return;
        Integer[] temp = new Integer[i];
        for (int j = 0; j < size(); j++){
            temp[j] = data[j];
        }
        data = temp;
    }
}
